﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Happy.Bases;
using Happy.Command;
using Happy.Application;
using Happy.Examples.OrderManagement.Commands.Orders;
using Happy.Examples.OrderManagement.Domain.Orders;


namespace Happy.Examples.OrderManagement.Application.Orders
{
    internal sealed class OrderCommandHandler : ApplicationService, ICommandHandler<CreateOrderCommand>
    {
        void ICommandHandler<CreateOrderCommand>.Handle(CreateOrderCommand command)
        {
            var orderFactory = this.Service<OrderFactory>();
            var orderRepository = this.Service<IOrderRepository>();

            var order = orderFactory.Create(CreateCommandInfo(command));

            if (command.Order.OrderItems != null)
            {
                foreach (var item in command.Order.OrderItems)
                {
                    order.AddOrderItem(new OrderItem(item.ProductId, item.Product, item.Price, item.Quantity));
                }
            }

            orderRepository.Save(order);
            orderRepository.UnitOfWork.Flush();
        }

        private static CustomerInfo CreateCommandInfo(CreateOrderCommand command)
        {
            return new CustomerInfo(
                command.Order.CustomerName,
                command.Order.CustomerAddress,
                command.Order.CustomerTel);
        }
    }
}
